<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>试卷管理 - 管理后台</title>
    <link th:href="@{/admin/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/admin/css/bootstrap-icons.css}" rel="stylesheet">
    <link th:href="@{/admin/css/admin.css}" rel="stylesheet">
    <style>
        .search-filters {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .table-container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #6c757d;
        }
        .question-preview {
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .multi-answers-container {
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #e9ecef;
            border-radius: 0.375rem;
            padding: 0.5rem;
            background-color: #f8f9fa;
        }
        .answer-item {
            background: white;
            border-radius: 0.25rem;
            padding: 0.25rem;
        }
        .answer-item:last-child {
            margin-bottom: 0 !important;
        }
        .multi-answers-container::-webkit-scrollbar {
            width: 4px;
        }
        .multi-answers-container::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 2px;
        }
        .multi-answers-container::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 2px;
        }
        .multi-answers-container::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" th:href="@{/admin}">
                <i class="bi bi-gear-fill me-2"></i>口语练习管理后台
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" th:href="@{/}" target="_blank">
                    <i class="bi bi-box-arrow-up-right me-1"></i>前台页面
                </a>
                <form th:action="@{/api/v1/auth/logout}" method="post" class="d-inline">
                    <button type="submit" class="btn btn-outline-light btn-sm">
                        <i class="bi bi-box-arrow-right me-1"></i>退出登录
                    </button>
                </form>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-2 bg-light sidebar">
                <div class="position-sticky pt-3">
                    <ul class="nav nav-pills flex-column">
                        <li class="nav-item">
                            <a th:href="@{/admin}" class="nav-link">
                                <i class="bi bi-house-door me-2"></i>仪表盘
                            </a>
                        </li>
                        <li class="nav-item">
                            <a th:href="@{/admin/users}" class="nav-link">
                                <i class="bi bi-people me-2"></i>用户管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a th:href="@{/admin/exam-papers}" class="nav-link active">
                                <i class="bi bi-file-text me-2"></i>试卷管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a th:href="@{/admin/classes}" class="nav-link">
                                <i class="bi bi-building me-2"></i>班级管理
                            </a>
                        </li>
                    </ul>
                </div>
            </div>

            <!-- 主内容 -->
            <main class="col-md-10 ms-sm-auto px-md-4">
                <!-- 页面标题 -->
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">
                        <i class="bi bi-file-text me-2"></i>试卷管理
                    </h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <button type="button" class="btn btn-primary btn-sm me-2" onclick="createExamPaper()">
                            <i class="bi bi-plus-lg me-1"></i>新增试卷
                        </button>
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="refreshExamPapers()">
                            <i class="bi bi-arrow-clockwise me-1"></i>刷新数据
                        </button>
                    </div>
                </div>

                <!-- 消息提示区域 -->
                <div id="messageArea"></div>

                <!-- 筛选区域 -->
                <div class="search-filters">
                    <div class="row">
                        <div class="col-md-3">
                            <label class="form-label">年级筛选</label>
                            <select class="form-select" id="gradeFilter" onchange="filterExamPapers()">
                                <option value="">所有年级</option>
                                <option value="1">一年级</option>
                                <option value="2">二年级</option>
                                <option value="3">三年级</option>
                                <option value="4">四年级</option>
                                <option value="5">五年级</option>
                                <option value="6">六年级</option>
                                <option value="7">七年级</option>
                                <option value="8">八年级</option>
                                <option value="9">九年级</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">试卷类型筛选</label>
                            <select class="form-select" id="typeFilter" onchange="filterExamPapers()">
                                <option value="">所有类型</option>
                                <option value="PRACTICE">练习试卷</option>
                                <option value="TEST">测试试卷</option>
                            </select>
                        </div>
                        <div class="col-md-3 d-flex align-items-end">
                            <button type="button" class="btn btn-secondary" onclick="clearFilters()">
                                <i class="bi bi-x-lg me-1"></i>清除筛选
                            </button>
                        </div>
                    </div>
                </div>

                <!-- 试卷列表 -->
                <div class="table-container">
                    <div id="loadingIndicator" class="text-center p-4" style="display: none;">
                        <div class="spinner-border" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="mt-2">加载试卷数据中...</p>
                    </div>
                    
                    <div id="examPapersTableContainer">
                        <div class="table-responsive">
                            <table class="table table-hover mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th>ID</th>
                                        <th>试卷标题</th>
                                        <th>目标年级</th>
                                        <th>试卷类型</th>
                                        <th>朗读内容</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="examPapersTableBody">
                                    <!-- 试卷数据将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div id="emptyState" class="empty-state" style="display: none;">
                        <i class="bi bi-file-text display-1"></i>
                        <h4 class="mt-3">没有找到试卷</h4>
                        <p>点击"新增试卷"按钮创建第一份试卷</p>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 试卷详情/编辑模态框 -->
    <div class="modal fade" id="examPaperModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">试卷详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="examPaperForm">
                        <input type="hidden" id="examPaperId" value="">
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">试卷标题 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="title" required>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">目标年级 <span class="text-danger">*</span></label>
                                <select class="form-select" id="targetGrade" required>
                                    <option value="">请选择年级</option>
                                    <option value="1">一年级</option>
                                    <option value="2">二年级</option>
                                    <option value="3">三年级</option>
                                    <option value="4">四年级</option>
                                    <option value="5">五年级</option>
                                    <option value="6">六年级</option>
                                    <option value="7">七年级</option>
                                    <option value="8">八年级</option>
                                    <option value="9">九年级</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">试卷类型 <span class="text-danger">*</span></label>
                                <select class="form-select" id="paperType" required>
                                    <option value="">请选择类型</option>
                                    <option value="PRACTICE">练习试卷</option>
                                    <option value="TEST">测试试卷</option>
                                </select>
                            </div>
                        </div>

                        <!-- 朗读训练 -->
                        <div class="card mb-3">
                            <div class="card-header">
                                <h6 class="card-title mb-0"><i class="bi bi-book me-2"></i>朗读训练</h6>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label">朗读文本内容 <span class="text-danger">*</span></label>
                                    <textarea class="form-control" id="readingContent" rows="4" placeholder="请输入英语短文内容" required></textarea>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">示范音频文件</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="readingAudioFileId" placeholder="音频文件ID" readonly>
                                        <input type="file" class="form-control" id="readingAudioFileIdFile" accept="audio/*" onchange="uploadReadingAudio(this)" style="display: none;">
                                        <button class="btn btn-outline-secondary" type="button" onclick="document.getElementById('readingAudioFileIdFile').click()">
                                            <i class="bi bi-upload"></i> 选择文件
                                        </button>
                                    </div>
                                    <small class="text-muted">上传朗读示范音频，供学生参考</small>
                                </div>
                            </div>
                        </div>

                        <!-- 情景问答 -->
                        <div class="card mb-3">
                            <div class="card-header">
                                <h6 class="card-title mb-0"><i class="bi bi-chat-dots me-2"></i>情景问答（5题）</h6>
                            </div>
                            <div class="card-body">
                                <div class="accordion" id="qaAccordion">
                                    <!-- 情景问答题目1 -->
                                    <div class="accordion-item">
                                        <h2 class="accordion-header">
                                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" 
                                                    data-bs-target="#qa1" id="qaBtn1">
                                                情景问答题目 1
                                            </button>
                                        </h2>
                                        <div id="qa1" class="accordion-collapse collapse" data-bs-parent="#qaAccordion">
                                            <div class="accordion-body">
                                                <div class="mb-3">
                                                    <label class="form-label">题目内容</label>
                                                    <textarea class="form-control" id="scenarioQa1" rows="2" required></textarea>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <label class="form-label">音频文件</label>
                                                        <div class="input-group">
                                                            <input type="text" class="form-control" id="scenarioQa1AudioFileId" placeholder="音频文件ID" readonly>
                                                            <input type="file" class="form-control" id="scenarioQa1AudioFileIdFile" accept="audio/*" onchange="uploadAudio(this, 1)" style="display: none;">
                                                            <button class="btn btn-outline-secondary" type="button" onclick="document.getElementById('scenarioQa1AudioFileIdFile').click()">
                                                                <i class="bi bi-upload"></i> 选择文件
                                                            </button>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label class="form-label">参考答案</label>
                                                        <div class="multi-answers-container" id="scenarioQa1AnswerContainer">
                                                            <div class="answer-item mb-2">
                                                                <div class="input-group">
                                                                    <input type="text" class="form-control answer-input" placeholder="输入参考答案">
                                                                    <button class="btn btn-outline-danger" type="button" onclick="removeAnswer(this)">
                                                                        <i class="bi bi-trash"></i>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <button class="btn btn-outline-primary btn-sm mt-1" type="button" onclick="addAnswer('scenarioQa1AnswerContainer')">
                                                            <i class="bi bi-plus"></i> 添加答案
                                                        </button>
                                                        <input type="hidden" id="scenarioQa1Answer">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <!-- 情景问答题目2 -->
                                    <div class="accordion-item">
                                        <h2 class="accordion-header">
                                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" 
                                                    data-bs-target="#qa2" id="qaBtn2">
                                                情景问答题目 2
                                            </button>
                                        </h2>
                                        <div id="qa2" class="accordion-collapse collapse" data-bs-parent="#qaAccordion">
                                            <div class="accordion-body">
                                                <div class="mb-3">
                                                    <label class="form-label">题目内容</label>
                                                    <textarea class="form-control" id="scenarioQa2" rows="2" required></textarea>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <label class="form-label">音频文件</label>
                                                        <div class="input-group">
                                                            <input type="text" class="form-control" id="scenarioQa2AudioFileId" placeholder="音频文件ID" readonly>
                                                            <input type="file" class="form-control" id="scenarioQa2AudioFileIdFile" accept="audio/*" onchange="uploadAudio(this, 2)" style="display: none;">
                                                            <button class="btn btn-outline-secondary" type="button" onclick="document.getElementById('scenarioQa2AudioFileIdFile').click()">
                                                                <i class="bi bi-upload"></i> 选择文件
                                                            </button>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label class="form-label">参考答案</label>
                                                        <div class="multi-answers-container" id="scenarioQa2AnswerContainer">
                                                            <div class="answer-item mb-2">
                                                                <div class="input-group">
                                                                    <input type="text" class="form-control answer-input" placeholder="输入参考答案">
                                                                    <button class="btn btn-outline-danger" type="button" onclick="removeAnswer(this)">
                                                                        <i class="bi bi-trash"></i>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <button class="btn btn-outline-primary btn-sm mt-1" type="button" onclick="addAnswer('scenarioQa2AnswerContainer')">
                                                            <i class="bi bi-plus"></i> 添加答案
                                                        </button>
                                                        <input type="hidden" id="scenarioQa2Answer">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <!-- 情景问答题目3 -->
                                    <div class="accordion-item">
                                        <h2 class="accordion-header">
                                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" 
                                                    data-bs-target="#qa3" id="qaBtn3">
                                                情景问答题目 3
                                            </button>
                                        </h2>
                                        <div id="qa3" class="accordion-collapse collapse" data-bs-parent="#qaAccordion">
                                            <div class="accordion-body">
                                                <div class="mb-3">
                                                    <label class="form-label">题目内容</label>
                                                    <textarea class="form-control" id="scenarioQa3" rows="2" required></textarea>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <label class="form-label">音频文件</label>
                                                        <div class="input-group">
                                                            <input type="text" class="form-control" id="scenarioQa3AudioFileId" placeholder="音频文件ID" readonly>
                                                            <input type="file" class="form-control" id="scenarioQa3AudioFileIdFile" accept="audio/*" onchange="uploadAudio(this, 3)" style="display: none;">
                                                            <button class="btn btn-outline-secondary" type="button" onclick="document.getElementById('scenarioQa3AudioFileIdFile').click()">
                                                                <i class="bi bi-upload"></i> 选择文件
                                                            </button>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label class="form-label">参考答案</label>
                                                        <div class="multi-answers-container" id="scenarioQa3AnswerContainer">
                                                            <div class="answer-item mb-2">
                                                                <div class="input-group">
                                                                    <input type="text" class="form-control answer-input" placeholder="输入参考答案">
                                                                    <button class="btn btn-outline-danger" type="button" onclick="removeAnswer(this)">
                                                                        <i class="bi bi-trash"></i>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <button class="btn btn-outline-primary btn-sm mt-1" type="button" onclick="addAnswer('scenarioQa3AnswerContainer')">
                                                            <i class="bi bi-plus"></i> 添加答案
                                                        </button>
                                                        <input type="hidden" id="scenarioQa3Answer">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <!-- 情景问答题目4 -->
                                    <div class="accordion-item">
                                        <h2 class="accordion-header">
                                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" 
                                                    data-bs-target="#qa4" id="qaBtn4">
                                                情景问答题目 4
                                            </button>
                                        </h2>
                                        <div id="qa4" class="accordion-collapse collapse" data-bs-parent="#qaAccordion">
                                            <div class="accordion-body">
                                                <div class="mb-3">
                                                    <label class="form-label">题目内容</label>
                                                    <textarea class="form-control" id="scenarioQa4" rows="2" required></textarea>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <label class="form-label">音频文件</label>
                                                        <div class="input-group">
                                                            <input type="text" class="form-control" id="scenarioQa4AudioFileId" placeholder="音频文件ID" readonly>
                                                            <input type="file" class="form-control" id="scenarioQa4AudioFileIdFile" accept="audio/*" onchange="uploadAudio(this, 4)" style="display: none;">
                                                            <button class="btn btn-outline-secondary" type="button" onclick="document.getElementById('scenarioQa4AudioFileIdFile').click()">
                                                                <i class="bi bi-upload"></i> 选择文件
                                                            </button>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label class="form-label">参考答案</label>
                                                        <div class="multi-answers-container" id="scenarioQa4AnswerContainer">
                                                            <div class="answer-item mb-2">
                                                                <div class="input-group">
                                                                    <input type="text" class="form-control answer-input" placeholder="输入参考答案">
                                                                    <button class="btn btn-outline-danger" type="button" onclick="removeAnswer(this)">
                                                                        <i class="bi bi-trash"></i>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <button class="btn btn-outline-primary btn-sm mt-1" type="button" onclick="addAnswer('scenarioQa4AnswerContainer')">
                                                            <i class="bi bi-plus"></i> 添加答案
                                                        </button>
                                                        <input type="hidden" id="scenarioQa4Answer">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <!-- 情景问答题目5 -->
                                    <div class="accordion-item">
                                        <h2 class="accordion-header">
                                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" 
                                                    data-bs-target="#qa5" id="qaBtn5">
                                                情景问答题目 5
                                            </button>
                                        </h2>
                                        <div id="qa5" class="accordion-collapse collapse" data-bs-parent="#qaAccordion">
                                            <div class="accordion-body">
                                                <div class="mb-3">
                                                    <label class="form-label">题目内容</label>
                                                    <textarea class="form-control" id="scenarioQa5" rows="2" required></textarea>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <label class="form-label">音频文件</label>
                                                        <div class="input-group">
                                                            <input type="text" class="form-control" id="scenarioQa5AudioFileId" placeholder="音频文件ID" readonly>
                                                            <input type="file" class="form-control" id="scenarioQa5AudioFileIdFile" accept="audio/*" onchange="uploadAudio(this, 5)" style="display: none;">
                                                            <button class="btn btn-outline-secondary" type="button" onclick="document.getElementById('scenarioQa5AudioFileIdFile').click()">
                                                                <i class="bi bi-upload"></i> 选择文件
                                                            </button>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label class="form-label">参考答案</label>
                                                        <div class="multi-answers-container" id="scenarioQa5AnswerContainer">
                                                            <div class="answer-item mb-2">
                                                                <div class="input-group">
                                                                    <input type="text" class="form-control answer-input" placeholder="输入参考答案">
                                                                    <button class="btn btn-outline-danger" type="button" onclick="removeAnswer(this)">
                                                                        <i class="bi bi-trash"></i>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <button class="btn btn-outline-primary btn-sm mt-1" type="button" onclick="addAnswer('scenarioQa5AnswerContainer')">
                                                            <i class="bi bi-plus"></i> 添加答案
                                                        </button>
                                                        <input type="hidden" id="scenarioQa5Answer">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 视听应答 -->
                        <div class="card mb-3">
                            <div class="card-header">
                                <h6 class="card-title mb-0"><i class="bi bi-headphones me-2"></i>视听应答（5题）</h6>
                            </div>
                            <div class="card-body">
                                <div class="accordion" id="listeningAccordion">
                                    <!-- 视听应答题目1 -->
                                    <div class="accordion-item">
                                        <h2 class="accordion-header">
                                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" 
                                                    data-bs-target="#listening1" id="listeningBtn1">
                                                视听应答题目 1
                                            </button>
                                        </h2>
                                        <div id="listening1" class="accordion-collapse collapse" data-bs-parent="#listeningAccordion">
                                            <div class="accordion-body">
                                                <div class="mb-3">
                                                    <label class="form-label">题目内容</label>
                                                    <textarea class="form-control" id="listeningQa1" rows="2" required></textarea>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <label class="form-label">图片文件</label>
                                                        <div class="input-group">
                                                            <input type="text" class="form-control" id="listeningQa1AudioFileId" placeholder="图片文件ID" readonly>
                                                            <input type="file" class="form-control" id="listeningQa1AudioFileIdFile" accept="image/*" onchange="uploadListeningAudio(this, 1)" style="display: none;">
                                                            <button class="btn btn-outline-secondary" type="button" onclick="document.getElementById('listeningQa1AudioFileIdFile').click()">
                                                                <i class="bi bi-upload"></i> 选择文件
                                                            </button>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label class="form-label">参考答案</label>
                                                        <div class="multi-answers-container" id="listeningQa1AnswerContainer">
                                                            <div class="answer-item mb-2">
                                                                <div class="input-group">
                                                                    <input type="text" class="form-control answer-input" placeholder="输入参考答案">
                                                                    <button class="btn btn-outline-danger" type="button" onclick="removeAnswer(this)">
                                                                        <i class="bi bi-trash"></i>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <button class="btn btn-outline-primary btn-sm mt-1" type="button" onclick="addAnswer('listeningQa1AnswerContainer')">
                                                            <i class="bi bi-plus"></i> 添加答案
                                                        </button>
                                                        <input type="hidden" id="listeningQa1Answer">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <!-- 视听应答题目2 -->
                                    <div class="accordion-item">
                                        <h2 class="accordion-header">
                                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" 
                                                    data-bs-target="#listening2" id="listeningBtn2">
                                                视听应答题目 2
                                            </button>
                                        </h2>
                                        <div id="listening2" class="accordion-collapse collapse" data-bs-parent="#listeningAccordion">
                                            <div class="accordion-body">
                                                <div class="mb-3">
                                                    <label class="form-label">题目内容</label>
                                                    <textarea class="form-control" id="listeningQa2" rows="2" required></textarea>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <label class="form-label">图片文件</label>
                                                        <div class="input-group">
                                                            <input type="text" class="form-control" id="listeningQa2AudioFileId" placeholder="图片文件ID" readonly>
                                                            <input type="file" class="form-control" id="listeningQa2AudioFileIdFile" accept="image/*" onchange="uploadListeningAudio(this, 2)" style="display: none;">
                                                            <button class="btn btn-outline-secondary" type="button" onclick="document.getElementById('listeningQa2AudioFileIdFile').click()">
                                                                <i class="bi bi-upload"></i> 选择文件
                                                            </button>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label class="form-label">参考答案</label>
                                                        <div class="multi-answers-container" id="listeningQa2AnswerContainer">
                                                            <div class="answer-item mb-2">
                                                                <div class="input-group">
                                                                    <input type="text" class="form-control answer-input" placeholder="输入参考答案">
                                                                    <button class="btn btn-outline-danger" type="button" onclick="removeAnswer(this)">
                                                                        <i class="bi bi-trash"></i>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <button class="btn btn-outline-primary btn-sm mt-1" type="button" onclick="addAnswer('listeningQa2AnswerContainer')">
                                                            <i class="bi bi-plus"></i> 添加答案
                                                        </button>
                                                        <input type="hidden" id="listeningQa2Answer">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <!-- 视听应答题目3 -->
                                    <div class="accordion-item">
                                        <h2 class="accordion-header">
                                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" 
                                                    data-bs-target="#listening3" id="listeningBtn3">
                                                视听应答题目 3
                                            </button>
                                        </h2>
                                        <div id="listening3" class="accordion-collapse collapse" data-bs-parent="#listeningAccordion">
                                            <div class="accordion-body">
                                                <div class="mb-3">
                                                    <label class="form-label">题目内容</label>
                                                    <textarea class="form-control" id="listeningQa3" rows="2" required></textarea>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <label class="form-label">图片文件</label>
                                                        <div class="input-group">
                                                            <input type="text" class="form-control" id="listeningQa3AudioFileId" placeholder="图片文件ID" readonly>
                                                            <input type="file" class="form-control" id="listeningQa3AudioFileIdFile" accept="image/*" onchange="uploadListeningAudio(this, 3)" style="display: none;">
                                                            <button class="btn btn-outline-secondary" type="button" onclick="document.getElementById('listeningQa3AudioFileIdFile').click()">
                                                                <i class="bi bi-upload"></i> 选择文件
                                                            </button>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label class="form-label">参考答案</label>
                                                        <div class="multi-answers-container" id="listeningQa3AnswerContainer">
                                                            <div class="answer-item mb-2">
                                                                <div class="input-group">
                                                                    <input type="text" class="form-control answer-input" placeholder="输入参考答案">
                                                                    <button class="btn btn-outline-danger" type="button" onclick="removeAnswer(this)">
                                                                        <i class="bi bi-trash"></i>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <button class="btn btn-outline-primary btn-sm mt-1" type="button" onclick="addAnswer('listeningQa3AnswerContainer')">
                                                            <i class="bi bi-plus"></i> 添加答案
                                                        </button>
                                                        <input type="hidden" id="listeningQa3Answer">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <!-- 视听应答题目4 -->
                                    <div class="accordion-item">
                                        <h2 class="accordion-header">
                                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" 
                                                    data-bs-target="#listening4" id="listeningBtn4">
                                                视听应答题目 4
                                            </button>
                                        </h2>
                                        <div id="listening4" class="accordion-collapse collapse" data-bs-parent="#listeningAccordion">
                                            <div class="accordion-body">
                                                <div class="mb-3">
                                                    <label class="form-label">题目内容</label>
                                                    <textarea class="form-control" id="listeningQa4" rows="2" required></textarea>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <label class="form-label">图片文件</label>
                                                        <div class="input-group">
                                                            <input type="text" class="form-control" id="listeningQa4AudioFileId" placeholder="图片文件ID" readonly>
                                                            <input type="file" class="form-control" id="listeningQa4AudioFileIdFile" accept="image/*" onchange="uploadListeningAudio(this, 4)" style="display: none;">
                                                            <button class="btn btn-outline-secondary" type="button" onclick="document.getElementById('listeningQa4AudioFileIdFile').click()">
                                                                <i class="bi bi-upload"></i> 选择文件
                                                            </button>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label class="form-label">参考答案</label>
                                                        <div class="multi-answers-container" id="listeningQa4AnswerContainer">
                                                            <div class="answer-item mb-2">
                                                                <div class="input-group">
                                                                    <input type="text" class="form-control answer-input" placeholder="输入参考答案">
                                                                    <button class="btn btn-outline-danger" type="button" onclick="removeAnswer(this)">
                                                                        <i class="bi bi-trash"></i>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <button class="btn btn-outline-primary btn-sm mt-1" type="button" onclick="addAnswer('listeningQa4AnswerContainer')">
                                                            <i class="bi bi-plus"></i> 添加答案
                                                        </button>
                                                        <input type="hidden" id="listeningQa4Answer">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <!-- 视听应答题目5 -->
                                    <div class="accordion-item">
                                        <h2 class="accordion-header">
                                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" 
                                                    data-bs-target="#listening5" id="listeningBtn5">
                                                视听应答题目 5
                                            </button>
                                        </h2>
                                        <div id="listening5" class="accordion-collapse collapse" data-bs-parent="#listeningAccordion">
                                            <div class="accordion-body">
                                                <div class="mb-3">
                                                    <label class="form-label">题目内容</label>
                                                    <textarea class="form-control" id="listeningQa5" rows="2" required></textarea>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <label class="form-label">图片文件</label>
                                                        <div class="input-group">
                                                            <input type="text" class="form-control" id="listeningQa5AudioFileId" placeholder="图片文件ID" readonly>
                                                            <input type="file" class="form-control" id="listeningQa5AudioFileIdFile" accept="image/*" onchange="uploadListeningAudio(this, 5)" style="display: none;">
                                                            <button class="btn btn-outline-secondary" type="button" onclick="document.getElementById('listeningQa5AudioFileIdFile').click()">
                                                                <i class="bi bi-upload"></i> 选择文件
                                                            </button>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label class="form-label">参考答案</label>
                                                        <div class="multi-answers-container" id="listeningQa5AnswerContainer">
                                                            <div class="answer-item mb-2">
                                                                <div class="input-group">
                                                                    <input type="text" class="form-control answer-input" placeholder="输入参考答案">
                                                                    <button class="btn btn-outline-danger" type="button" onclick="removeAnswer(this)">
                                                                        <i class="bi bi-trash"></i>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <button class="btn btn-outline-primary btn-sm mt-1" type="button" onclick="addAnswer('listeningQa5AnswerContainer')">
                                                            <i class="bi bi-plus"></i> 添加答案
                                                        </button>
                                                        <input type="hidden" id="listeningQa5Answer">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 话题表达 -->
                        <div class="card mb-3">
                            <div class="card-header">
                                <h6 class="card-title mb-0"><i class="bi bi-person-video me-2"></i>话题表达</h6>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label">话题简述 <span class="text-danger">*</span></label>
                                    <textarea class="form-control" id="topicBrief" rows="3" placeholder="请简要描述话题内容..." required></textarea>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">要点提示</label>
                                    <div class="multi-answers-container" id="keyPointsContainer">
                                        <div class="answer-item mb-2">
                                            <div class="input-group">
                                                <input type="text" class="form-control answer-input" placeholder="输入要点提示">
                                                <button class="btn btn-outline-danger" type="button" onclick="removeAnswer(this)">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    <button class="btn btn-outline-primary btn-sm mt-1" type="button" onclick="addAnswer('keyPointsContainer')">
                                        <i class="bi bi-plus"></i> 添加要点
                                    </button>
                                    <input type="hidden" id="keyPoints">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">参考答案</label>
                                    <div class="multi-answers-container" id="referenceAnswersContainer">
                                        <div class="answer-item mb-2">
                                            <div class="input-group">
                                                <input type="text" class="form-control answer-input" placeholder="输入参考答案">
                                                <button class="btn btn-outline-danger" type="button" onclick="removeAnswer(this)">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    <button class="btn btn-outline-primary btn-sm mt-1" type="button" onclick="addAnswer('referenceAnswersContainer')">
                                        <i class="bi bi-plus"></i> 添加答案
                                    </button>
                                    <input type="hidden" id="referenceAnswers">
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveExamPaper()">保存试卷</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 确认删除模态框 -->
    <div class="modal fade" id="deleteModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>确认要删除试卷 <strong id="deleteExamPaperTitle"></strong> 吗？</p>
                    <p class="text-danger small">此操作不可撤销！</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" onclick="executeDelete()">删除</button>
                </div>
            </div>
        </div>
    </div>

    <script th:src="@{/admin/js/bootstrap.bundle.min.js}"></script>
    <script>
        let allExamPapers = [];
        let filteredExamPapers = [];
        let pendingDeleteId = null;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadExamPapers();
        });

        // 加载试卷数据
        function loadExamPapers(params = {}) {
            showLoading(true);
            
            const queryParams = new URLSearchParams(params).toString();
            const url = `/api/v1/exam-papers${queryParams ? '?' + queryParams : ''}`;
            
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.code === 0) {
                        allExamPapers = data.data || [];
                        filteredExamPapers = [...allExamPapers];
                        renderExamPapers();
                    } else {
                        showMessage(data.message || '加载试卷数据失败', 'danger');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage('网络错误，请稍后重试', 'danger');
                })
                .finally(() => {
                    showLoading(false);
                });
        }

        // 筛选试卷
        function filterExamPapers() {
            const gradeFilter = document.getElementById('gradeFilter').value;
            const typeFilter = document.getElementById('typeFilter').value;
            
            const params = {};
            if (gradeFilter) params.grade = gradeFilter;
            if (typeFilter) params.type = typeFilter;
            
            if (Object.keys(params).length > 0) {
                loadExamPapers(params);
            } else {
                filteredExamPapers = [...allExamPapers];
                renderExamPapers();
            }
        }

        // 清除筛选
        function clearFilters() {
            document.getElementById('gradeFilter').value = '';
            document.getElementById('typeFilter').value = '';
            loadExamPapers();
        }

        // 刷新试卷列表
        function refreshExamPapers() {
            loadExamPapers();
        }

        // 渲染试卷表格
        function renderExamPapers() {
            const tbody = document.getElementById('examPapersTableBody');
            const emptyState = document.getElementById('emptyState');
            const tableContainer = document.getElementById('examPapersTableContainer');

            if (filteredExamPapers.length === 0) {
                tableContainer.style.display = 'none';
                emptyState.style.display = 'block';
                return;
            }

            tableContainer.style.display = 'block';
            emptyState.style.display = 'none';

            tbody.innerHTML = filteredExamPapers.map(paper => `
                <tr>
                    <td>${paper.id}</td>
                    <td><strong>${paper.title}</strong></td>
                    <td>
                        <span class="badge bg-primary">${paper.targetGrade}年级</span>
                    </td>
                    <td>
                        <span class="badge ${getPaperTypeBadgeClass(paper.paperType)}">
                            ${getPaperTypeDisplayName(paper.paperType)}
                        </span>
                    </td>
                    <td>
                        <div class="question-preview" title="${paper.readingContent}">
                            ${paper.readingContent}
                        </div>
                    </td>
                    <td>
                        <small class="text-muted">
                            ${formatDateTime(paper.createdTime)}
                        </small>
                    </td>
                    <td>
                        <div class="btn-group btn-group-sm" role="group">
                            <!-- 查看按钮已屏蔽
                            <button type="button" class="btn btn-outline-primary" onclick="viewExamPaper(${paper.id})">
                                <i class="bi bi-eye"></i>
                            </button>
                            -->
                            <button type="button" class="btn btn-outline-warning" onclick="editExamPaper(${paper.id})">
                                <i class="bi bi-pencil"></i>
                            </button>
                            <button type="button" class="btn btn-outline-danger" onclick="deleteExamPaper(${paper.id}, '${paper.title}')">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
            `).join('');
        }

        // 创建新试卷
        function createExamPaper() {
            clearForm();
            document.getElementById('modalTitle').textContent = '新增试卷';
            new bootstrap.Modal(document.getElementById('examPaperModal')).show();
        }

        // 查看试卷
        function viewExamPaper(id) {
            loadExamPaperDetails(id, true);
        }

        // 编辑试卷
        function editExamPaper(id) {
            loadExamPaperDetails(id, false);
        }

        // 加载试卷详情
        function loadExamPaperDetails(id, readOnly = false) {
            fetch(`/api/v1/exam-papers/${id}/raw`)
                .then(response => response.json())
                .then(data => {
                    if (data.code === 0) {
                        populateForm(data.data);
                        document.getElementById('modalTitle').textContent = readOnly ? '查看试卷' : '编辑试卷';
                        
                        const modal = new bootstrap.Modal(document.getElementById('examPaperModal'));
                        modal.show();
                        
                        if (readOnly) {
                            // 只读模式，禁用所有表单元素
                            document.querySelectorAll('#examPaperForm input, #examPaperForm textarea, #examPaperForm select').forEach(el => {
                                el.disabled = true;
                            });
                        } else {
                            // 编辑模式，禁用试题类型字段
                            document.getElementById('paperType').disabled = true;
                        }
                    } else {
                        showMessage(data.message || '加载试卷详情失败', 'danger');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage('网络错误，请稍后重试', 'danger');
                });
        }

        // 删除试卷
        function deleteExamPaper(id, title) {
            pendingDeleteId = id;
            document.getElementById('deleteExamPaperTitle').textContent = title;
            new bootstrap.Modal(document.getElementById('deleteModal')).show();
        }

        // 执行删除
        function executeDelete() {
            if (!pendingDeleteId) return;

            fetch(`/api/v1/exam-papers/${pendingDeleteId}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();
                
                if (data.code === 0) {
                    showMessage('试卷删除成功！', 'success');
                    setTimeout(() => {
                        loadExamPapers();
                    }, 1000);
                } else {
                    showMessage(data.message || '删除失败，请重试', 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();
                showMessage('网络错误，请检查连接后重试', 'danger');
            })
            .finally(() => {
                pendingDeleteId = null;
            });
        }

        // 保存试卷
        function saveExamPaper() {
            const formData = collectFormData();
            if (!validateForm(formData)) return;

            const isEdit = !!formData.id;
            const url = isEdit ? `/api/v1/exam-papers/${formData.id}` : '/api/v1/exam-papers';
            const method = isEdit ? 'PUT' : 'POST';

            fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 0) {
                    bootstrap.Modal.getInstance(document.getElementById('examPaperModal')).hide();
                    showMessage(`试卷${isEdit ? '更新' : '创建'}成功！`, 'success');
                    setTimeout(() => {
                        loadExamPapers();
                    }, 1000);
                } else {
                    showMessage(data.message || '保存失赅，请重试', 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('网络错误，请检查连接后重试', 'danger');
            });
        }

        // 收集表单数据
        function collectFormData() {
            // 收集多答案数据并更新隐藏字段
            document.getElementById('scenarioQa1Answer').value = collectMultiAnswers('scenarioQa1AnswerContainer');
            document.getElementById('scenarioQa2Answer').value = collectMultiAnswers('scenarioQa2AnswerContainer');
            document.getElementById('scenarioQa3Answer').value = collectMultiAnswers('scenarioQa3AnswerContainer');
            document.getElementById('scenarioQa4Answer').value = collectMultiAnswers('scenarioQa4AnswerContainer');
            document.getElementById('scenarioQa5Answer').value = collectMultiAnswers('scenarioQa5AnswerContainer');
            document.getElementById('listeningQa1Answer').value = collectMultiAnswers('listeningQa1AnswerContainer');
            document.getElementById('listeningQa2Answer').value = collectMultiAnswers('listeningQa2AnswerContainer');
            document.getElementById('listeningQa3Answer').value = collectMultiAnswers('listeningQa3AnswerContainer');
            document.getElementById('listeningQa4Answer').value = collectMultiAnswers('listeningQa4AnswerContainer');
            document.getElementById('listeningQa5Answer').value = collectMultiAnswers('listeningQa5AnswerContainer');
            document.getElementById('keyPoints').value = collectMultiAnswers('keyPointsContainer');
            document.getElementById('referenceAnswers').value = collectMultiAnswers('referenceAnswersContainer');
            
            return {
                id: document.getElementById('examPaperId').value || null,
                title: document.getElementById('title').value,
                targetGrade: parseInt(document.getElementById('targetGrade').value),
                paperType: document.getElementById('paperType').value,
                readingContent: document.getElementById('readingContent').value,
                scenarioQa1: document.getElementById('scenarioQa1').value,
                scenarioQa1AudioFileId: document.getElementById('scenarioQa1AudioFileId').value,
                scenarioQa1Answer: document.getElementById('scenarioQa1Answer').value,
                scenarioQa2: document.getElementById('scenarioQa2').value,
                scenarioQa2AudioFileId: document.getElementById('scenarioQa2AudioFileId').value,
                scenarioQa2Answer: document.getElementById('scenarioQa2Answer').value,
                scenarioQa3: document.getElementById('scenarioQa3').value,
                scenarioQa3AudioFileId: document.getElementById('scenarioQa3AudioFileId').value,
                scenarioQa3Answer: document.getElementById('scenarioQa3Answer').value,
                scenarioQa4: document.getElementById('scenarioQa4').value,
                scenarioQa4AudioFileId: document.getElementById('scenarioQa4AudioFileId').value,
                scenarioQa4Answer: document.getElementById('scenarioQa4Answer').value,
                scenarioQa5: document.getElementById('scenarioQa5').value,
                scenarioQa5AudioFileId: document.getElementById('scenarioQa5AudioFileId').value,
                scenarioQa5Answer: document.getElementById('scenarioQa5Answer').value,
                listeningQa1: document.getElementById('listeningQa1').value,
                listeningQa1AudioFileId: document.getElementById('listeningQa1AudioFileId').value,
                listeningQa1Answer: document.getElementById('listeningQa1Answer').value,
                listeningQa2: document.getElementById('listeningQa2').value,
                listeningQa2AudioFileId: document.getElementById('listeningQa2AudioFileId').value,
                listeningQa2Answer: document.getElementById('listeningQa2Answer').value,
                listeningQa3: document.getElementById('listeningQa3').value,
                listeningQa3AudioFileId: document.getElementById('listeningQa3AudioFileId').value,
                listeningQa3Answer: document.getElementById('listeningQa3Answer').value,
                listeningQa4: document.getElementById('listeningQa4').value,
                listeningQa4AudioFileId: document.getElementById('listeningQa4AudioFileId').value,
                listeningQa4Answer: document.getElementById('listeningQa4Answer').value,
                listeningQa5: document.getElementById('listeningQa5').value,
                listeningQa5AudioFileId: document.getElementById('listeningQa5AudioFileId').value,
                listeningQa5Answer: document.getElementById('listeningQa5Answer').value,
                topicBrief: document.getElementById('topicBrief').value,
                keyPoints: document.getElementById('keyPoints').value,
                referenceAnswers: document.getElementById('referenceAnswers').value
            };
        }

        // 填充表单数据
        function populateForm(data) {
            document.getElementById('examPaperId').value = data.id || '';
            document.getElementById('title').value = data.title || '';
            document.getElementById('targetGrade').value = data.targetGrade || '';
            document.getElementById('paperType').value = data.paperType || 'PRACTICE';
            document.getElementById('readingContent').value = data.readingContent || '';
            
            // 填充5道情景问答题
            for (let i = 1; i <= 5; i++) {
                document.getElementById(`scenarioQa${i}`).value = data[`scenarioQa${i}`] || '';
                document.getElementById(`scenarioQa${i}AudioFileId`).value = data[`scenarioQa${i}AudioFileId`] || '';
                document.getElementById(`scenarioQa${i}Answer`).value = data[`scenarioQa${i}Answer`] || '';
                
                // 填充多答案数据
                populateMultiAnswers(`scenarioQa${i}AnswerContainer`, data[`scenarioQa${i}Answer`] || '');
            }
            
            // 填充5道视听应答题
            for (let i = 1; i <= 5; i++) {
                document.getElementById(`listeningQa${i}`).value = data[`listeningQa${i}`] || '';
                document.getElementById(`listeningQa${i}AudioFileId`).value = data[`listeningQa${i}AudioFileId`] || '';
                document.getElementById(`listeningQa${i}Answer`).value = data[`listeningQa${i}Answer`] || '';
                
                // 填充多答案数据
                populateMultiAnswers(`listeningQa${i}AnswerContainer`, data[`listeningQa${i}Answer`] || '');
            }
            
            document.getElementById('topicBrief').value = data.topicBrief || '';
            document.getElementById('keyPoints').value = data.keyPoints || '';
            document.getElementById('referenceAnswers').value = data.referenceAnswers || '';
            
            // 填充话题表达多答案数据
            populateMultiAnswers('keyPointsContainer', data.keyPoints || '');
            populateMultiAnswers('referenceAnswersContainer', data.referenceAnswers || '');
        }

        // 清空表单
        function clearForm() {
            document.getElementById('examPaperForm').reset();
            document.getElementById('examPaperId').value = '';
            
            // 清空多答案容器，每个容器重置为一个空输入框
            const answerContainers = [
                'scenarioQa1AnswerContainer',
                'scenarioQa2AnswerContainer', 
                'scenarioQa3AnswerContainer',
                'scenarioQa4AnswerContainer',
                'scenarioQa5AnswerContainer',
                'listeningQa1AnswerContainer',
                'listeningQa2AnswerContainer',
                'listeningQa3AnswerContainer',
                'listeningQa4AnswerContainer',
                'listeningQa5AnswerContainer',
                'keyPointsContainer',
                'referenceAnswersContainer'
            ];
            
            answerContainers.forEach(containerId => {
                populateMultiAnswers(containerId, '');
            });
            
            // 重新启用所有表单元素
            document.querySelectorAll('#examPaperForm input, #examPaperForm textarea, #examPaperForm select').forEach(el => {
                el.disabled = false;
            });
        }

        // 表单验证
        function validateForm(data) {
            if (!data.title.trim()) {
                showMessage('请输入试卷标题', 'danger');
                return false;
            }
            if (!data.targetGrade) {
                showMessage('请选择目标年级', 'danger');
                return false;
            }
            if (!data.paperType) {
                showMessage('请选择试卷类型', 'danger');
                return false;
            }
            if (!data.readingContent.trim()) {
                showMessage('请输入朗读训练内容', 'danger');
                return false;
            }
            
            // 检查5道情景问答题是否都有内容
            for (let i = 1; i <= 5; i++) {
                if (!data[`scenarioQa${i}`].trim()) {
                    showMessage(`请填写情景问答题目${i}`, 'danger');
                    return false;
                }
            }
            
            if (!data.topicBrief.trim()) {
                showMessage('请输入话题简述', 'danger');
                return false;
            }
            
            return true;
        }

        // 显示加载状态
        function showLoading(show) {
            const loadingIndicator = document.getElementById('loadingIndicator');
            const tableContainer = document.getElementById('examPapersTableContainer');
            
            if (show) {
                loadingIndicator.style.display = 'block';
                tableContainer.style.display = 'none';
            } else {
                loadingIndicator.style.display = 'none';
                tableContainer.style.display = 'block';
            }
        }

        // 显示消息
        function showMessage(message, type = 'success') {
            const messageArea = document.getElementById('messageArea');
            const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
            
            messageArea.innerHTML = `
                <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
                    <i class="bi bi-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} me-2"></i>
                    ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `;
            
            // 自动隐藏成功消息
            if (type === 'success') {
                setTimeout(() => {
                    const alert = messageArea.querySelector('.alert');
                    if (alert) {
                        const bsAlert = new bootstrap.Alert(alert);
                        bsAlert.close();
                    }
                }, 3000);
            }
        }

        // 上传音频文件
        function uploadAudio(fileInput, questionNumber) {
            const file = fileInput.files[0];
            if (!file) return;
            
            // 验证文件类型
            if (!file.type.startsWith('audio/')) {
                showMessage('请选择音频文件', 'danger');
                fileInput.value = '';
                return;
            }
            
            // 验证文件大小 (10MB)
            if (file.size > 10 * 1024 * 1024) {
                showMessage('文件大小不能超过10MB', 'danger');
                fileInput.value = '';
                return;
            }
            
            const formData = new FormData();
            formData.append('file', file);
            
            // 显示上传状态
            const targetInputId = `scenarioQa${questionNumber}AudioFileId`;
            const targetInput = document.getElementById(targetInputId);
            const originalPlaceholder = targetInput.placeholder;
            const originalValue = targetInput.value;
            
            targetInput.value = '上传中...';
            targetInput.style.color = '#6c757d';
            
            fetch('/api/v1/exam-papers/upload-audio', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 0) {
                    // 上传成功，设置fileId
                    targetInput.value = data.data.fileId || '';
                    targetInput.style.color = '#198754'; // 绿色表示成功
                    showMessage(`音频文件上传成功！文件名: ${data.data.fileName}`, 'success');
                } else {
                    showMessage(data.message || '上传失败', 'danger');
                    targetInput.value = originalValue;
                    targetInput.style.color = '';
                }
            })
            .catch(error => {
                console.error('Upload error:', error);
                showMessage('上传失败，请重试', 'danger');
                targetInput.value = originalValue;
                targetInput.style.color = '';
            })
            .finally(() => {
                // 清空文件选择框，允许重新选择同一文件
                fileInput.value = '';
            });
        }

        // 上传视听应答图片文件
        function uploadListeningAudio(fileInput, questionNumber) {
            const file = fileInput.files[0];
            if (!file) {
                return;
            }
            
            // 验证文件类型
            if (!file.type.startsWith('image/')) {
                showMessage('请选择图片文件', 'danger');
                fileInput.value = '';
                return;
            }
            
            // 验证文件大小 (10MB)
            const maxSize = 10 * 1024 * 1024;
            if (file.size > maxSize) {
                showMessage('文件大小不能超过10MB', 'danger');
                fileInput.value = '';
                return;
            }
            
            const formData = new FormData();
            formData.append('file', file);
            
            // 显示上传状态
            const targetInputId = `listeningQa${questionNumber}AudioFileId`;
            const targetInput = document.getElementById(targetInputId);
            
            targetInput.value = '上传中...';
            targetInput.style.color = '#6c757d';
            
            fetch('/api/v1/exam-papers/upload-audio', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 0) {
                    targetInput.value = data.data.fileId || '';
                    targetInput.style.color = '#198754';
                    showMessage(`视听应答图片文件上传成功！文件名: ${data.data.fileName}`, 'success');
                } else {
                    targetInput.value = '';
                    targetInput.style.color = '#dc3545';
                    showMessage(data.message || '上传失败', 'danger');
                }
            })
            .catch(error => {
                console.error('Upload error:', error);
                targetInput.value = '';
                targetInput.style.color = '#dc3545';
                showMessage('上传失败，请重试', 'danger');
            })
            .finally(() => {
                // 清空文件选择框，允许重新选择同一文件
                fileInput.value = '';
            });
        }

        // 获取试卷类型显示名称
        function getPaperTypeDisplayName(paperType) {
            switch(paperType) {
                case 'PRACTICE': return '练习试卷';
                case 'TEST': return '测试试卷';
                default: return '未知类型';
            }
        }
        
        // 获取试卷类型徽章样式
        function getPaperTypeBadgeClass(paperType) {
            switch(paperType) {
                case 'PRACTICE': return 'bg-success';
                case 'TEST': return 'bg-warning text-dark';
                default: return 'bg-secondary';
            }
        }

        // 添加答案输入框
        function addAnswer(containerId) {
            const container = document.getElementById(containerId);
            const answerItem = document.createElement('div');
            answerItem.className = 'answer-item mb-2';
            answerItem.innerHTML = `
                <div class="input-group">
                    <input type="text" class="form-control answer-input" placeholder="输入参考答案">
                    <button class="btn btn-outline-danger" type="button" onclick="removeAnswer(this)">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            `;
            container.appendChild(answerItem);
        }

        // 删除答案输入框
        function removeAnswer(button) {
            const container = button.closest('.multi-answers-container');
            const answerItems = container.querySelectorAll('.answer-item');
            
            // 至少保留一个答案输入框
            if (answerItems.length > 1) {
                button.closest('.answer-item').remove();
            } else {
                // 如果只有一个，清空内容而不删除
                const input = button.closest('.answer-item').querySelector('.answer-input');
                input.value = '';
            }
        }

        // 收集多答案数据
        function collectMultiAnswers(containerId) {
            const container = document.getElementById(containerId);
            const inputs = container.querySelectorAll('.answer-input');
            const answers = [];
            
            inputs.forEach(input => {
                const value = input.value.trim();
                if (value) {
                    answers.push(value);
                }
            });
            
            return answers.join('&');
        }

        // 显示多答案数据
        function populateMultiAnswers(containerId, answersString) {
            const container = document.getElementById(containerId);
            
            // 清空现有内容
            container.innerHTML = '';
            
            if (!answersString) {
                // 如果没有数据，添加一个空的输入框
                addAnswer(containerId);
                return;
            }
            
            // 分割答案并创建输入框
            const answers = answersString.split('&').filter(answer => answer.trim());
            
            if (answers.length === 0) {
                addAnswer(containerId);
                return;
            }
            
            answers.forEach(answer => {
                const answerItem = document.createElement('div');
                answerItem.className = 'answer-item mb-2';
                answerItem.innerHTML = `
                    <div class="input-group">
                        <input type="text" class="form-control answer-input" placeholder="输入参考答案" value="${answer.trim()}">
                        <button class="btn btn-outline-danger" type="button" onclick="removeAnswer(this)">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                `;
                container.appendChild(answerItem);
            });
        }

        // 格式化日期时间
        function formatDateTime(dateTime) {
            if (!dateTime) return '未知';
            
            try {
                const date = new Date(dateTime);
                return date.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            } catch (e) {
                return '无效日期';
            }
        }
    </script>
    <script>
        // DOM 修正：
        // - 情景问答：将“题目内容”改为“情景问答问题”
        // - 视听应答：移除题目文本，左侧改为 图片文件 + 题目音频文件
        function fixExamPaperFormDom() {
            try {
                // 情景问答标签修正
                for (let i = 1; i <= 5; i++) {
                    const ta = document.getElementById(`scenarioQa${i}`);
                    if (ta) {
                        const block = ta.closest('.mb-3');
                        const label = block ? block.querySelector('label.form-label') : null;
                        if (label) label.textContent = '情景问答问题';
                    }
                }

                // 视听应答结构修正（题目文本 + 图片 + 问题音频 + 答案）
                for (let i = 1; i <= 5; i++) {
                    const body = document.querySelector(`#listening${i} .accordion-body`);
                    if (!body) continue;

                    // 保留题目文本块，但修改标签
                    const ta = body.querySelector(`#listeningQa${i}`);
                    if (ta) {
                        const mb3 = ta.closest('.mb-3');
                        const label = mb3 ? mb3.querySelector('label.form-label') : null;
                        if (label) label.textContent = '题目文本';
                    }

                    // 左列改造为：图片 + 音频
                    const row = body.querySelector('.row');
                    if (!row) continue;
                    const leftCol = row.querySelector('.col-md-6');
                    if (leftCol) {
                        leftCol.innerHTML = `
                            <label class="form-label">题目图片文件</label>
                            <div class="input-group mb-2">
                                <input type="text" class="form-control" id="listeningQa${i}ImageFileId" placeholder="图片文件ID" readonly>
                                <input type="file" class="form-control" id="listeningQa${i}ImageFileIdFile" accept="image/*" onchange="uploadListeningImage(this, ${i})" style="display: none;">
                                <button class="btn btn-outline-secondary" type="button" onclick="document.getElementById('listeningQa${i}ImageFileIdFile').click()">
                                    <i class="bi bi-upload"></i> 选择文件
                                </button>
                            </div>
                            <label class="form-label">题目音频文件</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="listeningQa${i}AudioFileId" placeholder="音频文件ID" readonly>
                                <input type="file" class="form-control" id="listeningQa${i}AudioFileIdFile" accept="audio/*" onchange="uploadListeningAudio(this, ${i})" style="display: none;">
                                <button class="btn btn-outline-secondary" type="button" onclick="document.getElementById('listeningQa${i}AudioFileIdFile').click()">
                                    <i class="bi bi-upload"></i> 选择文件
                                </button>
                            </div>
                        `;
                    }
                }
            } catch (e) {
                console.error('fixExamPaperFormDom error:', e);
            }
        }

        // 覆盖：收集表单数据（JSON v2 结构）
        function collectFormData() {
            // 汇总多答案字符串到隐藏域
            document.getElementById('scenarioQa1Answer').value = collectMultiAnswers('scenarioQa1AnswerContainer');
            document.getElementById('scenarioQa2Answer').value = collectMultiAnswers('scenarioQa2AnswerContainer');
            document.getElementById('scenarioQa3Answer').value = collectMultiAnswers('scenarioQa3AnswerContainer');
            document.getElementById('scenarioQa4Answer').value = collectMultiAnswers('scenarioQa4AnswerContainer');
            document.getElementById('scenarioQa5Answer').value = collectMultiAnswers('scenarioQa5AnswerContainer');
            document.getElementById('listeningQa1Answer').value = collectMultiAnswers('listeningQa1AnswerContainer');
            document.getElementById('listeningQa2Answer').value = collectMultiAnswers('listeningQa2AnswerContainer');
            document.getElementById('listeningQa3Answer').value = collectMultiAnswers('listeningQa3AnswerContainer');
            document.getElementById('listeningQa4Answer').value = collectMultiAnswers('listeningQa4AnswerContainer');
            document.getElementById('listeningQa5Answer').value = collectMultiAnswers('listeningQa5AnswerContainer');
            document.getElementById('keyPoints').value = collectMultiAnswers('keyPointsContainer');
            document.getElementById('referenceAnswers').value = collectMultiAnswers('referenceAnswersContainer');

            // 组装 JSON 数组
            const dialogueQuestions = [];
            for (let i = 1; i <= 5; i++) {
                dialogueQuestions.push({
                    number: i,
                    question: (document.getElementById(`scenarioQa${i}`)?.value || '').trim(),
                    audioFileId: (document.getElementById(`scenarioQa${i}AudioFileId`)?.value || '').trim(),
                    answer: (document.getElementById(`scenarioQa${i}Answer`)?.value || '').trim()
                });
            }

            const listeningQuestions = [];
            for (let i = 1; i <= 5; i++) {
                listeningQuestions.push({
                    number: i,
                    questionText: (document.getElementById(`listeningQa${i}`)?.value || '').trim(),
                    questionFileId: (document.getElementById(`listeningQa${i}AudioFileId`)?.value || '').trim(),
                    imageFileId: (document.getElementById(`listeningQa${i}ImageFileId`)?.value || '').trim(),
                    answer: (document.getElementById(`listeningQa${i}Answer`)?.value || '').trim()
                });
            }

            return {
                id: document.getElementById('examPaperId').value || null,
                title: document.getElementById('title').value,
                targetGrade: parseInt(document.getElementById('targetGrade').value),
                paperType: document.getElementById('paperType').value,
                readingContent: document.getElementById('readingContent').value,
                readingAudioFileId: document.getElementById('readingAudioFileId').value,
                dialogueQuestions,
                listeningQuestions,
                topicBrief: document.getElementById('topicBrief').value,
                keyPoints: document.getElementById('keyPoints').value,
                referenceAnswers: document.getElementById('referenceAnswers').value
            };
        }

        // 覆盖：回填表单数据（JSON v2 结构）
        function populateForm(data) {
            // ⚠️ 关键修复：先修正DOM结构，再填充数据
            fixExamPaperFormDom();

            document.getElementById('examPaperId').value = data.id || '';
            document.getElementById('title').value = data.title || '';
            document.getElementById('targetGrade').value = data.targetGrade || '';
            document.getElementById('paperType').value = data.paperType || 'PRACTICE';
            document.getElementById('readingContent').value = data.readingContent || '';
            document.getElementById('readingAudioFileId').value = data.readingAudioFileId || '';

            // 回填情景问答
            if (Array.isArray(data.dialogueQuestions)) {
                data.dialogueQuestions.forEach(q => {
                    const i = q.number;
                    if (!i) return;
                    const question = q.question || '';
                    const audioFileId = q.audioFileId || '';
                    const answer = q.answer || '';
                    const ta = document.getElementById(`scenarioQa${i}`);
                    if (ta) ta.value = question;
                    const audioIdEl = document.getElementById(`scenarioQa${i}AudioFileId`);
                    if (audioIdEl) audioIdEl.value = audioFileId;
                    const hiddenAnswer = document.getElementById(`scenarioQa${i}Answer`);
                    if (hiddenAnswer) hiddenAnswer.value = answer;
                    populateMultiAnswers(`scenarioQa${i}AnswerContainer`, answer);
                });
            }

            // 回填视听应答
            if (Array.isArray(data.listeningQuestions)) {
                console.log('开始填充视听应答数据，数量:', data.listeningQuestions.length);
                data.listeningQuestions.forEach(q => {
                    const i = q.number;
                    if (!i) return;
                    const questionText = q.questionText || '';
                    const imageId = q.imageFileId || '';
                    const audioId = q.questionFileId || '';
                    const answer = q.answer || '';
                    console.log(`视听应答题目${i}:`, { questionText, imageId, audioId, answer });

                    const textEl = document.getElementById(`listeningQa${i}`);
                    const imgEl = document.getElementById(`listeningQa${i}ImageFileId`);
                    const audioEl = document.getElementById(`listeningQa${i}AudioFileId`);
                    const hiddenAnswer = document.getElementById(`listeningQa${i}Answer`);

                    console.log(`视听应答题目${i}元素查找:`, {
                        textEl: !!textEl,
                        imgEl: !!imgEl,
                        audioEl: !!audioEl,
                        hiddenAnswer: !!hiddenAnswer
                    });

                    if (textEl) textEl.value = questionText;
                    if (imgEl) imgEl.value = imageId;
                    if (audioEl) audioEl.value = audioId;
                    if (hiddenAnswer) hiddenAnswer.value = answer;
                    populateMultiAnswers(`listeningQa${i}AnswerContainer`, answer);
                });
            } else {
                console.log('视听应答数据为空或非数组:', data.listeningQuestions);
            }

            document.getElementById('topicBrief').value = data.topicBrief || '';
            document.getElementById('keyPoints').value = data.keyPoints || '';
            document.getElementById('referenceAnswers').value = data.referenceAnswers || '';
            populateMultiAnswers('keyPointsContainer', data.keyPoints || '');
            populateMultiAnswers('referenceAnswersContainer', data.referenceAnswers || '');
        }

        // 覆盖：校验（基于 JSON 结构）
        function validateForm(data) {
            if (!data.title || !data.title.trim()) {
                showMessage('请输入试卷标题', 'danger');
                return false;
            }
            if (!data.targetGrade) {
                showMessage('请选择目标年级', 'danger');
                return false;
            }
            if (!data.paperType) {
                showMessage('请选择试卷类型', 'danger');
                return false;
            }
            if (!data.readingContent || !data.readingContent.trim()) {
                showMessage('请输入识读训练内容', 'danger');
                return false;
            }

            if (!Array.isArray(data.dialogueQuestions) || data.dialogueQuestions.length !== 5) {
                showMessage('情景问答应为5道题', 'danger');
                return false;
            }
            for (let i = 0; i < 5; i++) {
                if (!data.dialogueQuestions[i].question || !data.dialogueQuestions[i].question.trim()) {
                    showMessage(`请填写情景问答问题${i + 1}`, 'danger');
                    return false;
                }
            }

            if (!data.topicBrief || !data.topicBrief.trim()) {
                showMessage('请输入话题简述', 'danger');
                return false;
            }
            return true;
        }

        // 覆盖：视听应答-音频上传（题目音频）
        function uploadListeningAudio(fileInput, questionNumber) {
            const file = fileInput.files[0];
            if (!file) return;
            if (!file.type.startsWith('audio/')) {
                showMessage('请选择音频文件', 'danger');
                fileInput.value = '';
                return;
            }
            if (file.size > 10 * 1024 * 1024) {
                showMessage('文件大小不能超过10MB', 'danger');
                fileInput.value = '';
                return;
            }
            const formData = new FormData();
            formData.append('file', file);
            const targetInputId = `listeningQa${questionNumber}AudioFileId`;
            const targetInput = document.getElementById(targetInputId);
            const originalValue = targetInput ? targetInput.value : '';
            if (targetInput) {
                targetInput.value = '上传中...';
                targetInput.style.color = '#6c757d';
            }
            fetch('/api/v1/exam-papers/upload-audio', { method: 'POST', body: formData })
                .then(r => r.json())
                .then(data => {
                    if (data.code === 0) {
                        if (targetInput) {
                            targetInput.value = data.data.fileId || '';
                            targetInput.style.color = '#198754';
                        }
                        showMessage(`音频文件上传成功：${data.data.fileName}`, 'success');
                    } else {
                        if (targetInput) {
                            targetInput.value = originalValue;
                            targetInput.style.color = '';
                        }
                        showMessage(data.message || '上传失败', 'danger');
                    }
                })
                .catch(err => {
                    console.error('Upload error:', err);
                    if (targetInput) {
                        targetInput.value = originalValue;
                        targetInput.style.color = '';
                    }
                    showMessage('上传失败，请重试', 'danger');
                })
                .finally(() => { fileInput.value = ''; });
        }

        // 新增：视听应答-图片上传（题目图片）
        function uploadListeningImage(fileInput, questionNumber) {
            const file = fileInput.files[0];
            if (!file) return;
            if (!file.type.startsWith('image/')) {
                showMessage('请选择图片文件', 'danger');
                fileInput.value = '';
                return;
            }
            if (file.size > 10 * 1024 * 1024) {
                showMessage('文件大小不能超过10MB', 'danger');
                fileInput.value = '';
                return;
            }
            const formData = new FormData();
            formData.append('file', file);
            const targetInputId = `listeningQa${questionNumber}ImageFileId`;
            const targetInput = document.getElementById(targetInputId);
            const originalValue = targetInput ? targetInput.value : '';
            if (targetInput) {
                targetInput.value = '上传中...';
                targetInput.style.color = '#6c757d';
            }
            fetch('/api/v1/exam-papers/upload-image', { method: 'POST', body: formData })
                .then(r => r.json())
                .then(data => {
                    if (data.code === 0) {
                        if (targetInput) {
                            targetInput.value = data.data.fileId || '';
                            targetInput.style.color = '#198754';
                        }
                        showMessage(`图片文件上传成功：${data.data.fileName}`, 'success');
                    } else {
                        if (targetInput) {
                            targetInput.value = originalValue;
                            targetInput.style.color = '';
                        }
                        showMessage(data.message || '上传失败', 'danger');
                    }
                })
                .catch(err => {
                    console.error('Upload error:', err);
                    if (targetInput) {
                        targetInput.value = originalValue;
                        targetInput.style.color = '';
                    }
                    showMessage('上传失败，请重试', 'danger');
                })
                .finally(() => { fileInput.value = ''; });
        }

        // 上传朗读示范音频
        function uploadReadingAudio(fileInput) {
            const file = fileInput.files[0];
            if (!file) return;

            // 验证文件类型
            if (!file.type.startsWith('audio/')) {
                showMessage('请选择音频文件', 'danger');
                fileInput.value = '';
                return;
            }

            // 验证文件大小 (10MB)
            if (file.size > 10 * 1024 * 1024) {
                showMessage('文件大小不能超过10MB', 'danger');
                fileInput.value = '';
                return;
            }

            const formData = new FormData();
            formData.append('file', file);

            // 显示上传状态
            const targetInput = document.getElementById('readingAudioFileId');
            const originalValue = targetInput.value;

            targetInput.value = '上传中...';
            targetInput.style.color = '#6c757d';

            fetch('/api/v1/exam-papers/upload-audio', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 0) {
                    // 上传成功，设置fileId
                    targetInput.value = data.data.fileId || '';
                    targetInput.style.color = '#198754'; // 绿色表示成功
                    showMessage(`朗读示范音频上传成功！文件名: ${data.data.fileName}`, 'success');
                } else {
                    showMessage(data.message || '上传失败', 'danger');
                    targetInput.value = originalValue;
                    targetInput.style.color = '';
                }
            })
            .catch(error => {
                console.error('Upload error:', error);
                showMessage('上传失败，请重试', 'danger');
                targetInput.value = originalValue;
                targetInput.style.color = '';
            })
            .finally(() => {
                // 清空文件选择框，允许重新选择同一文件
                fileInput.value = '';
            });
        }

        // 页面加载后执行 DOM 修正一次
        document.addEventListener('DOMContentLoaded', () => {
            fixExamPaperFormDom();
        });
    </script>
</body>
</html>
